using FastDevTemplate.Common.Util;
using FastDevTemplate.DataAccess;
using FastDevTemplate.DataAccess.Entities;
using FastDevTemplate.Service.Base;
using FastDevTemplate.Service.Interface;
using FastDevTemplate.Service.Interface.DTO;
using Microsoft.EntityFrameworkCore;

namespace FastDevTemplate.Service;

public class PermissionService(FastDevTemplateDbContext dbContext) : 
    BaseQueryService<
        Permission,
        string,
        PermissionResultDto,
        PermissionResultDto>(dbContext),
    IPermissionService
{
    public async Task<int> SetListByServiceAsync(string client, List<PermissionAddDto> permissions)
    {
        await using var transaction = await Dao.Database.BeginTransactionAsync();
        try
        {
            var permissionIDList = permissions.Select(item => item.ID);
            await DbSet.Where(item => item.Service == client).Where(item => !permissionIDList.Contains(item.ID)).ExecuteDeleteAsync();
            var query = DbSet.Where(item => item.Service == client);
            
            var permissonAddList = permissions.Select(
                item => {
                    var entity = ObjectMapper.Map<Permission>(item);
                    entity.Service = client;
                    return entity;
                })
                .Where(item => !query.Select(p => p.ID).ToList().Contains(item.ID));
            
            await DbSet.AddRangeAsync(permissonAddList);

            var count = await Dao.SaveChangesAsync();
            if (count <= 0)
                return ErrorHandling(ErrorType.DataBaseSaveError, nameof(SetListByServiceAsync));
            await transaction.CommitAsync();
            return count;
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            return ErrorHandling(ErrorType.DataBaseSaveError, e);
        }
    }

    public async Task<ICollection<PermissionResultDto>> GetListByServiceAsync(string client)
    {
        return await DbSet.Where(item => item.Service == client)
            .Select(item => ObjectMapper.Map<PermissionResultDto>(item))
            .ToListAsync();
    }
}